﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Profile;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using Facade;
using System.Collections;
using System.Data;

namespace IronOne.SalesOne.SalesOneWeb.CustomerServices
{
    public partial class SearchClaim : SOSecurityPage, IDataPage, IntTest
    {
        private int pageNo = 1;
        StructureFacade facade;
        int userType;
        public List<Branch> brnch;
        public List<SalesOneUnit> un;
        public List<string> so;


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["f"] != null)
                {
                    MassageSummery("IIS502");

                    Session.Remove("f");
                }

                if (Session["s"] != null)
                {
                    MassageSummery("IIS401");
                    Session.Remove("s");
                }

                facade = new StructureFacade();
                string csType = string.Empty;
                CodeFacade fac = new CodeFacade();



                ValidateUserCredentials(Request.Url.LocalPath);



                //lblError.Text = "";

                if (!IsPostBack)
                {

                    if (Request.QueryString["cs"] != null)
                    {
                        csType = Request.QueryString["cs"].ToString();
                    }

                    switch (csType)
                    {
                        case "cl":
                            //lblHeader.Text = "Search Claim";

                            List<ClaimStatus> cs = fac.GetClaimStatuss("CodeId ASC", 1);
                            ClaimStatus cs1 = new ClaimStatus();
                            cs1.CodeId = -1;
                            cs1.Description = "Select...";
                            cs.Insert(0, cs1);
                            drpClaimStatus.DataSource = cs;
                            drpClaimStatus.DataValueField = "CodeId";
                            drpClaimStatus.DataTextField = "Description";
                            drpClaimStatus.DataBind();

                            lblStatus.Text = "Claim Status";
                            lblNo.Text = "Claim No";
                            btnUpdate.Visible = false;
                            break;

                        case "com":

                            //lblHeader.Text = "Search Complaint";

                            List<ComplaintStatus> compSt = fac.GetComplaintStatuss("CodeId ASC", 1);
                            ComplaintStatus com = new ComplaintStatus();
                            com.CodeId = -1;
                            com.Description = "Select...";
                            compSt.Insert(0, com);
                            drpClaimStatus.DataSource = compSt;
                            drpClaimStatus.DataValueField = "CodeId";
                            drpClaimStatus.DataTextField = "Description";
                            drpClaimStatus.DataBind();

                            lblStatus.Text = "Complaint Status";
                            lblNo.Text = "Complaint No";

                            break;
                        default:
                            break;
                    }



                    User user = facade.GetUser(User.Identity.Name);
                    UserInformation info = facade.GetUserInformation(User.Identity.Name);
                    userType = info.UserType;

                    bool flag = false;

                    if (userType == 4)
                    {
                        if (user.SoCode != null)
                        {
                            //drpSoCodes.Items.Add(user.SoCode);
                            //drpSoCodes.SelectedIndex = drpSoCodes.Items.Count - 1;

                            populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                            //drpSoCodes.Enabled = false;
                        }
                        else
                            populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                        flag = true;
                    }

                    if (flag == true)
                    {
                        ListItem ls = new ListItem();
                        ls.Text = info.UnitName;
                        ls.Value = info.UnitId.ToString();

                        drpUnit.Items.Add(ls);
                        drpUnit.SelectedIndex = drpUnit.Items.Count - 1;

                        drpUnit.Enabled = false;
                    }
                    else if (userType == 3)
                    {
                        populateUnits(facade.GetUnitsForBranch(user.NodeId));
                        addDefaultItem(drpSoCodes);
                        flag = true;
                    }

                    if (flag == true)
                    {
                        ListItem ls = new ListItem();
                        ls.Text = info.BranchName;
                        ls.Value = info.BranchId.ToString();
                        drpBranch.Items.Add(ls);
                        drpBranch.SelectedIndex = drpBranch.Items.Count - 1;

                        drpBranch.Enabled = false;
                    }
                    else if (userType == 2)
                    {
                        populateBranches(facade.GetBranchesForGroup(user.NodeId));
                        addDefaultItem(drpUnit);
                        addDefaultItem(drpSoCodes);
                        flag = true;
                    }

                    if (userType == 1)
                        populateBranches(facade.GetBranches("BranchName ASC"));
                    addDefaultItem(drpUnit);
                    addDefaultItem(drpSoCodes);


                }
            }
            catch (Exception)
            {
                
            }

            

        }


        private void populateBranches(List<Branch> branches)
        {
            try
            {
                drpBranch.DataSource = branches;
                drpBranch.DataTextField = "BranchName";
                drpBranch.DataValueField = "BranchID";
                drpBranch.DataBind();

                addDefaultItem(drpBranch);
            }
            catch (Exception)
            {
                
            }
            
        }



        private void populateUnits(List<SalesOneUnit> units)
        {
            try
            {
                drpUnit.DataSource = units;
                drpUnit.DataTextField = "Name";
                drpUnit.DataValueField = "UnitID";
                drpUnit.DataBind();

                addDefaultItem(drpUnit);
            }
            catch (Exception)
            {
                
            }
            
        }

        private void populateSOCodes(List<string> users)
        {
            try
            {
                drpSoCodes.Items.Clear();
                foreach (string str in users)
                {
                    drpSoCodes.Items.Add(str);
                }
                addDefaultItem(drpSoCodes);
            }
            catch (Exception)
            {
                
            }
            
        }

        private void addDefaultItem(DropDownList ddl)
        {
            try
            {
                ListItem newItem = new ListItem("Select...");
                ddl.Items.Insert(0, newItem);
            }
            catch (Exception)
            {
                
            }
            
        }

        private void SetOnlyDefault(DropDownList ddl)
        {
            try
            {
                ListItem newItem = new ListItem("Select...");
                ddl.Items.Insert(0, newItem);
                ddl.DataBind();
            }
            catch (Exception)
            {
            }
            

        }

        protected void drpBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (drpBranch.SelectedIndex > 0)
                {
                    populateUnits(facade.GetUnitsInBranch(int.Parse(drpBranch.SelectedValue)));
                    drpUnit.SelectedIndex = 0;
                    so = new List<string>();
                    populateSOCodes(so);
                }
                else
                {
                    List<SalesOneUnit> units = new List<SalesOneUnit>();
                    populateUnits(units);

                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception)
            {
                
            }
            
        }

        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (drpUnit.SelectedIndex > 0)
                {
                    populateSOCodes(facade.GetSOsInUnit(int.Parse(drpUnit.SelectedValue)));
                }
                else
                {
                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception)
            {
            }
            

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pageNo = 1;
            string csType = string.Empty;

            if (Request.QueryString["cs"] != null)
            {
                csType = Request.QueryString["cs"].ToString();
            }

            switch (csType)
            {
                case "cl":
                    searchClaim("cl",1);
                    break;
                case "com":
                    searchClaim("com",1);
                    break;
                default:
                    break;
            }


        }


        private void searchClaim(string type, int pageNo)
        {
            try
            {
                CustomerFacade cusFac = new CustomerFacade();

                string claimNo = txtClaimNo.Text;
                string contractId = txtContractNo.Text;
                string customerId = string.Empty;
                string status = string.Empty;
                int branchId;
                int unitId;
                string soCode = string.Empty;

                if (!string.IsNullOrEmpty(txtClientId.Text))
                {
                    customerId = txtClientId.Text;
                }


                if (drpClaimStatus.SelectedValue != "-1")
                {
                    status = drpClaimStatus.SelectedValue;
                }

                if (drpBranch.SelectedValue != "Select...")
                {
                    branchId = int.Parse(drpBranch.SelectedValue);
                    Branch brs = facade.GetBranch(branchId);
                    brnch = new List<Branch>();
                    brnch.Add(brs);
                }

                if (drpUnit.SelectedValue != "Select..." && drpUnit.SelectedIndex != -1)
                {
                    unitId = int.Parse(drpUnit.SelectedValue);
                    SalesOneUnit sun = facade.GetUnit(unitId);
                    un = new List<SalesOneUnit>();
                    un.Add(sun);
                }

                if (drpSoCodes.SelectedValue != "Select..." && drpSoCodes.Items.Count > 0)
                {
                    soCode = drpSoCodes.SelectedValue;
                    so = new List<string>();
                    so.Add(soCode);
                }



                SearchCS clSearch = new SearchCS();


                clSearch.ContractId = contractId;
                clSearch.Status = status;
                clSearch.Brnch = brnch;
                clSearch.Unt = un;
                clSearch.SOCode = so;
                clSearch.ClaimNo = claimNo;
                if (!string.IsNullOrEmpty(customerId))
                {
                    clSearch.ClientId = customerId;
                }


                if (pageNo == 1)
                {
                    UCGrid1.SetText("1");
                }


                if (type == "cl")
                {
                    if (!string.IsNullOrEmpty(status) && (brnch == null || un == null))
                    {
                        MassageSummery("IIS518");
                    }
                    else
                    {
                        List<Claim> clList = cusFac.searchClaim(clSearch, pageNo);
                        if (clList.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                        {
                            UCGrid1.IsLastPage = (cusFac.searchClaim(clSearch, pageNo + 1)).Count > 0 ? false : true;
                        }
                        CodeFacade cFacs = new CodeFacade();

                        DataTable usrTable = new DataTable();
                        DataRow newRow;

                        usrTable.Columns.Add("Claim No");
                        usrTable.Columns.Add("SO Code");
                        usrTable.Columns.Add("Contract No");
                        usrTable.Columns.Add("Client Name");
                        usrTable.Columns.Add("Client Id");
                        usrTable.Columns.Add("Pending Reason");
                        usrTable.Columns.Add("Status");
                        usrTable.Columns.Add("Date Assigned");

                        //hidden
                        usrTable.Columns.Add("Reply Date");
                        usrTable.Columns.Add("Remarks");

                        if (clList != null)
                        {
                            foreach (Claim cl in clList)
                            {
                                if (cl != null)
                                {
                                    newRow = usrTable.NewRow();

                                    newRow[0] = cl.ClaimNo;
                                    newRow[1] = cl.SOCode;
                                    newRow[2] = cl.ContractNo;
                                    if (!string.IsNullOrEmpty(cl.CustomerId) || cl.CustomerId != null)
                                    {
                                        newRow[3] = cusFac.GetCustomer(cl.CustomerId).FirstName;
                                        newRow[4] = cl.CustomerId;
                                    }


                                    newRow[5] = cl.PendingReason;
                                    if (cl.ClaimStatus != 0 || cl.ClaimStatus != null)
                                    {
                                        newRow[6] = cFacs.GetClaimStatus((int)cl.ClaimStatus).Description;
                                    }

                                    newRow[7] = cl.AssignDate;
                                    newRow[8] = cl.ReplyDate;
                                    newRow[9] = cl.Remarks;

                                    usrTable.Rows.Add(newRow);



                                }
                                else
                                {
                                    btnView.Visible = false;
                                }
                            }

                        }



                        if (usrTable.Rows.Count > 0)
                        {
                            btnView.Visible = true;
                        }
                        else
                        {
                            MassageSummery("IIS504");
                            //lblError.Text = "No data to display";
                            btnView.Visible = false;
                        }

                        

                        int[] dispArr = { 1, 10, 11 };
                        UCGrid1.SetDataSource(usrTable, dispArr);

                    }


                }
                else if (type == "com")
                {

                    if (string.IsNullOrEmpty(status) || brnch == null || un == null)
                    {
                        DataTable dt = new DataTable();
                        int[] dispArr = { 1, 10, 11 };
                        UCGrid1.SetDataSource(dt, dispArr);
                        btnView.Visible = false;
                        btnUpdate.Visible = false;
                        MassageSummery("IIS517");
                    }
                    else
                    {
                        List<Complaint> cmList = cusFac.SearchComplaint(clSearch, pageNo);
                        if (cmList.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                        {
                            UCGrid1.IsLastPage = (cusFac.SearchComplaint(clSearch, pageNo + 1)).Count > 0 ? false : true;
                        }
                        CodeFacade cFacs = new CodeFacade();

                        DataTable usrTable = new DataTable();
                        DataRow newRow;

                        usrTable.Columns.Add("Complaint No");
                        usrTable.Columns.Add("SO Code");
                        usrTable.Columns.Add("Contract No");
                        usrTable.Columns.Add("Client Name");
                        usrTable.Columns.Add("Client Id");
                        usrTable.Columns.Add("Status");
                        usrTable.Columns.Add("Date Assigned");

                        //hidden
                        usrTable.Columns.Add("Reply Date");
                        usrTable.Columns.Add("Remarks");
                        usrTable.Columns.Add("Last Up Date");
                        usrTable.Columns.Add("Type");
                        usrTable.Columns.Add("Sub Type");
                        usrTable.Columns.Add("Action Req");
                        usrTable.Columns.Add("Inform Meth");


                        if (cmList != null)
                        {
                            foreach (Complaint co in cmList)
                            {
                                if (co != null)
                                {
                                    newRow = usrTable.NewRow();

                                    newRow[0] = co.ComplaintId;
                                    newRow[1] = co.SOCode;
                                    newRow[2] = co.ContractNo;
                                    if (!string.IsNullOrEmpty(co.CustomerId) && co.CustomerId != null)
                                    {
                                        newRow[3] = cusFac.GetCustomer(co.CustomerId).FirstName;
                                        newRow[4] = co.CustomerId;
                                    }



                                    if (co.ComplaintStatus != 0 && co.ComplaintStatus != null)
                                    {
                                        newRow[5] = cFacs.GetComplaintStatus((int)co.ComplaintStatus).Description;
                                    }

                                    newRow[6] = co.AssignDate;
                                    //hidden
                                    newRow[7] = co.ReplyDate;
                                    newRow[8] = co.Remarks;
                                    newRow[9] = co.LastUpdated;

                                    if (co.ComplaintType != 0 && co.ComplaintType != null)
                                    {
                                        newRow[10] = cFacs.GetComplaintType((int)co.ComplaintType).Description;
                                    }

                                    //newRow[10] = co.ComplaintType;
                                    if (co.ComplaintSubType != 0 && co.ComplaintSubType != null)
                                    {
                                        newRow[11] = cFacs.GetCompaintSubType((int)co.ComplaintSubType).Description;
                                    }

                                    //newRow[11] = co.ComplaintSubType;
                                    newRow[12] = co.ActionRequired;
                                    newRow[13] = co.InformMethod;


                                    usrTable.Rows.Add(newRow);



                                }
                                else
                                {
                                    btnView.Visible = false;
                                    btnUpdate.Visible = false;
                                }
                            }
                        }



                        if (usrTable.Rows.Count > 0)
                        {
                            btnView.Visible = true;
                            btnUpdate.Visible = true;
                        }
                        else
                        {
                            btnView.Visible = false;
                            btnUpdate.Visible = false;
                            MassageSummery("IIS504");
                            //lblError.Text = "No data to display";
                        }

                        int[] dispArr = { 1, 10, 11, 12, 13, 14, 15 };
                        UCGrid1.SetDataSource(usrTable, dispArr);
                    }


                }
            }
            catch (Exception)
            {
                
            }
            
        
        }

        #region IDataPage Members

        public void Create()
        {
            
        }

        public void View()
        {
            
        }

        public void Update()
        {
            
        }

        public void Delete()
        {
            
        }

        public void Cancel()
        {
            
        }

        public void GetId(GridViewRow row)
        {
            string csType = string.Empty;

            if (Request.QueryString["cs"] != null)
            {
                csType = Request.QueryString["cs"].ToString();
            }

            if (csType == "cl")
            {
                Session["ClaimRow"] = row;
            }
            else
            {
                Session["CompRow"] = row;
            }
            
        }

        #endregion

        protected void btnView_Click(object sender, EventArgs e)
        {
            try
            {
                string csType = string.Empty;

                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                if (csType == "cl")
                {
                    if (Session["ClaimRow"] == null)
                    {
                        Session["ClaimRow"] = ((GridViewRow)Session["firstRow"]);
                        Session.Remove("firstRow");
                    }

                }
                else
                {
                    if (Session["CompRow"] == null)
                    {
                        Session["CompRow"] = ((GridViewRow)Session["firstRow"]);
                        Session.Remove("firstRow");
                    }
                }



                if (csType == "cl")
                {
                    if (Session["ClaimRow"] != null)
                    {
                        Response.Redirect("~/CustomerServices/ViewClaimDetails.aspx");
                    }
                    else
                    {
                        MassageSummery("IIS503");
                        //lblError.Text = "Please select a claim";
                    }

                }
                else
                {
                    if (Session["CompRow"] != null)
                    {
                        Response.Redirect("~/CustomerServices/ViewComplaintDetails.aspx?a=v");
                    }
                    else
                    {
                        MassageSummery("IIS503");
                        //lblError.Text = "Please select a claim";
                    }

                }
            }
            catch (Exception)
            {
                

            }
            
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                string csType = string.Empty;

                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                if (csType == "cl")
                {
                    if (Session["ClaimRow"] == null)
                    {
                        Session["ClaimRow"] = ((GridViewRow)Session["firstRow"]);
                        Session.Remove("firstRow");
                    }

                }
                else
                {
                    if (Session["CompRow"] == null)
                    {
                        Session["CompRow"] = ((GridViewRow)Session["firstRow"]);
                        Session.Remove("firstRow");
                    }
                }




                if (Session["CompRow"] != null)
                {
                    Response.Redirect("~/CustomerServices/ViewComplaintDetails.aspx?a=u");
                }
                else
                {
                    MassageSummery("IIS503");
                    //lblError.Text = "Please select a claim";
                }
            }
            catch (Exception)
            {
                

            }
            
        }

        #region IntTest Members

        public void Next()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
                    UCGrid1.SetText(pageNo.ToString());

                }
                else
                {
                    pageNo = 2;
                    UCGrid1.SetText("2");

                }


                string csType = string.Empty;
                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                switch (csType)
                {
                    case "cl":
                        searchClaim("cl", pageNo);
                        break;
                    case "com":
                        searchClaim("com", pageNo);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {
                
            }
            

        }

        public void Previous()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                    UCGrid1.SetText(pageNo.ToString());


                    string csType = string.Empty;
                    if (Request.QueryString["cs"] != null)
                    {
                        csType = Request.QueryString["cs"].ToString();
                    }


                    switch (csType)
                    {
                        case "cl":
                            searchClaim("cl", pageNo);
                            break;
                        case "com":
                            searchClaim("com", pageNo);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception)
            {

            }
            

        }

        public void Go()
        {
            try
            {
                string csType = string.Empty;
                if (Request.QueryString["cs"] != null)
                {
                    csType = Request.QueryString["cs"].ToString();
                }


                int p = int.Parse(UCGrid1.GetText());
                if (p != 0)
                {
                    try
                    {
                        switch (csType)
                        {
                            case "cl":
                                searchClaim("cl", p);
                                break;
                            case "com":
                                searchClaim("com", p);
                                break;
                            default:
                                break;
                        }

                        pageNo = p;
                    }
                    catch (Exception)
                    {

                        throw;
                    }


                }
            }
            catch (Exception)
            {

            }
            
        }

        #endregion
    }
}
